package com.zhongya.example.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.LinearInterpolator

class AnimWaveView : View{

    var mPaint : Paint = Paint()
    var mPath = Path()
    val mItemWaveLength = 1200

    var dx = 0


    constructor(context: Context) : super(context) {

    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        mPaint.color = Color.RED
//        mPaint.style = Paint.Style.STROKE
        mPaint.style = Paint.Style.FILL
//        mPaint.strokeWidth = 2f

        val animator = ValueAnimator.ofInt(0,mItemWaveLength)
        animator.duration = 2000
        animator.repeatCount = ValueAnimator.INFINITE
//        animator.interpolator = LinearInterpolator()
        animator.interpolator = AccelerateDecelerateInterpolator()
        animator.addUpdateListener {
            dx =  it.animatedValue as Int
            postInvalidate()
        }
        animator.start()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        mPath.reset()
        val originY = 600f
        val halfWaveLen = mItemWaveLength/2f
        mPath.moveTo((-mItemWaveLength + dx).toFloat(),originY)

        for (i in -mItemWaveLength .. width+mItemWaveLength step mItemWaveLength) {
            mPath.rQuadTo(halfWaveLen/2,-100f,halfWaveLen,0f)
            mPath.rQuadTo(halfWaveLen/2,100f,halfWaveLen,0f)
        }

        //封闭区间
        mPath.lineTo(width.toFloat(),height.toFloat())
        mPath.lineTo(0f,height.toFloat())
        mPath.close()


        canvas?.drawPath(mPath,mPaint)


    }
}